<template>
  <div>
    <div class="topBtn">
      <div class="sizeBig"><span>用户管理</span></div>
      <div>
        <el-button @click="configuration " type="primary"><i class="iconfont icon-zhongzhimima"></i> 配置工位</el-button>
        <el-button @click="newSetPass" type="primary"><i class="iconfont icon-zhongzhimima"></i> 重置密码</el-button>
        <el-button @click="exportExcel" type="primary"><i class="iconfont icon-icon-"></i> 导出</el-button>
        <el-button @click="dimission" type="primary"><i class="iconfont icon-lizhi"></i> 离职</el-button>
        <el-button @click="add" type="primary"><i class="iconfont icon-addNew"></i> 新增</el-button>
        <el-button @click="changecheck" icon="el-icon-edit" type="primary">修改</el-button>
        <el-button @click="removedata" icon="el-icon-delete" type="primary">删除</el-button>
      </div>
    </div>
    <div class="message">
      <p class="character">对车间进行新增改查等常规管理操作。 <span class="skip">查看帮助文档</span></p>
    </div>
    <div class="inputcontent">
      <el-input class="inSearch" placeholder="请输入内容" v-model="search"></el-input>
      <el-select class="select" placeholder="请选择" v-model="value">
        <el-option
          :key="item.value"
          :label="item.label"
          :value="item.value"
          v-for="item in options">
        </el-option>
      </el-select>
      <div class="iconSearch"></div>
    </div>
    <div class="tablesize">
      <Table :reset="reset" id="out-table" v-on:changeData="changedata" v-on:getId="getListId"></Table>
    </div>
    <div class="block">
      <el-pagination
        :page-size="1"
        :page-sizes="[10,20,50,100]"
        :total=total
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <!-- 新增弹出框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="新增数据"
      width="600px"
    >
      <el-form :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="140px" ref="ruleForm">
        <el-form-item label="用户名：" prop="userName">
          <el-input style="width:350px" v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="工号：" prop="jobNum">
          <el-input style="width:350px" v-model="ruleForm.jobNum"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="realName">
          <el-input style="width:350px" v-model="ruleForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select placeholder="请选择" style="width:350px" v-model="ruleForm.sex">
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.valueData"
              v-for="item in option">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input style="width:350px" v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="组织部门ID：" prop="departmentID">
          <!-- <el-input v-model="ruleForm.departmentID" style="width:350px"></el-input>  -->
          <el-select placeholder="请选择" style="width:350px" v-model="ruleForm.departmentID">
            <el-option
              :key="item.DepartmentID"
              :label="item.DepartmentName"
              :value="item.DepartmentID"
              v-for="item in departmentData">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色ID：" prop="roleID">
          <!-- <el-input v-model="ruleForm.departmentID" style="width:350px"></el-input>  -->
          <el-select placeholder="请选择" style="width:350px" v-model="ruleForm.roleID">
            <el-option
              :key="item.RoleID"
              :label="item.RoleName"
              :value="item.RoleID"
              v-for="item in roleData">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作电话：" prop="workPhone">
          <el-input style="width:350px" v-model="ruleForm.workPhone"></el-input>
        </el-form-item>
        <el-form-item label="手机电话：" prop="mobelPhone">
          <el-input style="width:350px" v-model="ruleForm.mobelPhone"></el-input>
        </el-form-item>
        <el-form-item label="企业微信号：" prop="weChatID">
          <el-input style="width:350px" v-model="ruleForm.weChatID"></el-input>
        </el-form-item>
        <el-form-item label="QQ号码：" prop="qq">
          <el-input style="width:350px" v-model="ruleForm.qq"></el-input>
        </el-form-item>

        <el-form-item label="是否为领导：" prop="Isleader">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-model="ruleForm['Isleader']">
          </el-switch>
        </el-form-item>

        <el-form-item>
          <el-button @click="submitReset('ruleForm')" type="primary">关闭</el-button>
          <el-button @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      :visible.sync="showadd"
      title="编辑信息"
      width="600px"
    >
      <el-form :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="140px" ref="ruleForm">
        <el-form-item label="用户名：" prop="userName">
          <el-input style="width:350px" v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="工号：" prop="jobNum">
          <el-input style="width:350px" v-model="ruleForm.jobNum"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="realName">
          <el-input style="width:350px" v-model="ruleForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select placeholder="请选择" style="width:350px" v-model="ruleForm.sex">
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.valueData"
              v-for="item in option">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input style="width:350px" v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="组织部门ID：" prop="departmentID">
          <!-- <el-input v-model="ruleForm.departmentID" style="width:350px"></el-input>  -->
          <el-select placeholder="请选择" style="width:350px" v-model="ruleForm.departmentID">
            <el-option
              :key="item.DepartmentID"
              :label="item.DepartmentName"
              :value="item.DepartmentID"
              v-for="item in departmentData">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色ID：" prop="roleID">
          <!-- <el-input v-model="ruleForm.departmentID" style="width:350px"></el-input>  -->
          <el-select placeholder="请选择" style="width:350px" v-model="ruleForm.roleID">
            <el-option
              :key="item.RoleID"
              :label="item.RoleName"
              :value="item.RoleID"
              v-for="item in roleData">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作电话：" prop="workPhone">
          <el-input style="width:350px" v-model="ruleForm.workPhone"></el-input>
        </el-form-item>
        <el-form-item label="手机电话：" prop="mobelPhone">
          <el-input style="width:350px" v-model="ruleForm.mobelPhone"></el-input>
        </el-form-item>
        <el-form-item label="企业微信号：" prop="weChatID">
          <el-input style="width:350px" v-model="ruleForm.weChatID"></el-input>
        </el-form-item>
        <el-form-item label="QQ号码：" prop="qq">
          <el-input style="width:350px" v-model="ruleForm.qq"></el-input>
        </el-form-item>

        <el-form-item label="是否为领导：" prop="Isleader">
          <el-switch

            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-model="ruleForm['Isleader']">
          </el-switch>
        </el-form-item>

        <el-form-item>
          <el-button @click="submitReset('ruleForm')" type="primary">关闭</el-button>
          <el-button @click="changeForm('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 配置工位 -->
    <el-dialog :close-on-click-modal='false' :visible.sync="conDialogVisible" center title="配置工位" width="700px">
      <el-table
        :data="userStationList"
        class="table start-print"
        height="400px"
        style="width: 100%;borderTop: 1px solid #ccc;">
        <el-table-column align="center" label="线体">
          <template scope="scope">
            <el-select placeholder="请选择" v-model="scope.row.Line.LineId">
              <el-option
                :key="index"
                :label="item.Name"
                :value="item.LineId"
                v-for="(item,index) in lineData"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center" label="工位">
          <template scope="scope">
            <el-select placeholder="请选择" v-model="scope.row.WorkStation.WorkstationId">
              <el-option
                :key="index"
                :label="item.Name"
                :value="item.WorkstationId"
                v-for="(item,index) in stationData"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center" label="工序">
          <template scope="scope">
            <el-select placeholder="请选择" v-model="scope.row.Tech.TechId">
              <el-option
                :key="index"
                :label="item.Name"
                :value="item.TechId"
                v-for="(item,index) in techData"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="打印机">
          <template scope="scope">
            <el-input v-model="scope.row.PrinterName"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div @click="add1" style="marginTop:10px;">
        <span class="skip">添加</span>
      </div>
      <div class="botBtn" style="marginLeft:190px;">
        <el-button @click="conDialogVisible=false" class="quxiao" style="marginRight:20px;">取消</el-button>
        <el-button @click="onSubmit" type="primary">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Table from './components/userControlTable'
  import operation from '@/mixins/operation'
  import {
    newSetPass,
    dimissionApi,
    getUserWorkStationList,
    commitUserWorkStation,
    getAllDepartmentList,
    getAllRoleList
  } from '@/api/userControl'
  import { getLineList } from '@/api/linebody'
  import { getWorkStationList } from '@/api/station'
  import { getTechPageList } from '@/api/process'
  import { delay } from '@/utils/autoSearch'

  export default {
    name: 'userControl',
    mixins: [operation],
    data() {
      return {
        lineData: [],
        stationData: [],
        techData: [],
        userStationList: [],
        departmentData: [],
        roleData: [],
        jsonItem: [],
        search: '',    //搜索
        showadd: false,    //修改数据
        options: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, {
          value: '选项3',
          label: '蚵仔煎'
        }, {
          value: '选项4',
          label: '龙须面'
        }, {
          value: '选项5',
          label: '北京烤鸭'
        }],
        option: [{
          valueData: '0',
          label: '男'
        }, {
          valueData: '1',
          label: '女'
        }
        ],

        value: '',   //下拉框的数据
        dialogVisible: false,   //新增弹出框
        passVisible: false,   //重置密码
        conDialogVisible: false, // 配置工位
        module: 'userControl',
        addlist: [], //勾选传过来的数据
        checkIds: [],   //勾选的id数组
        UserID: '',  //空指针
        ruleForm: {
          userName: '',   //用户名
          jobNum: '',   //工号
          realName: '',   //真实姓名
          sex: '',   //性别
          iconUrl: '',   //头像路径
          email: '',//邮箱
          departmentID: '',//组织部门ID
          roleID: '',  //角色id值
          workPhone: '',//工作电话
          mobelPhone: '',//手机号码
          weChatID: '',//微信号
          qq: '',//	QQ号码

          Isleader:'',
        },
        rules: {
          userName: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
          ],
          jobNum: [
            { required: true, message: '请输入用工工号', trigger: 'blur' },
            { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '请输入真实姓名', trigger: 'blur' },
            { min: 1, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入用户邮箱', trigger: 'blur' },
            { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }
          ],
          departmentID: [
            { required: true, message: '请输入组织部门ID', trigger: 'blur' }
          ],
          workPhone: [
            { required: true, message: '请输入工作电话号码', trigger: 'blur' },
            { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
          ],
          mobelPhone: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '长度在 11个字符', trigger: 'blur' }
          ],
          weChatID: [
            { required: true, message: '请输入企业微信号', trigger: 'blur' },
            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
          ],
          qq: [
            { required: true, message: '请输入qq号', trigger: 'blur' },
            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
          ],
          Isleader:[

          ]

        }
      }
    },
    components: {
      Table
    },
    watch: {
      //用来监听页面变量的改变
      //监听搜索，300ms执行一次fetchData方法（去搜索）
      search() {
        delay(() => {
          this.fetchData()
        }, 300)
      }
    },
    methods: {
      // 自动搜索的方法
      async fetchData(val) {
        this.initialize({ keyName: this.search, userStatu: -1, page: 1, pageSize: 2 })
      },
      changecheck() {
        if (this.addlist.length == 0) {
          alert('最少勾选一名员工')
        } else if (this.addlist.length > 1) {
          alert('不可勾选多名员工')
        } else {
          this.showadd = true
          console.log(this.addlist)
          this.UserID = this.addlist[0].UserID
          this.ruleForm.userName = this.addlist[0].UserName
          this.ruleForm.jobNum = this.addlist[0].JobNum
          this.ruleForm.realName = this.addlist[0].RealName
          this.ruleForm.sex = this.addlist[0].SexFormat
          this.ruleForm.email = this.addlist[0].Email
          this.ruleForm.departmentID = this.addlist[0].DepartmentID
          this.ruleForm.roleID = this.addlist[0].RoleID
          this.ruleForm.workPhone = this.addlist[0].WorkPhone
          this.ruleForm.mobelPhone = this.addlist[0].MobilePhone
          this.ruleForm.weChatID = this.addlist[0].WeChatID
          this.ruleForm.qq = this.addlist[0].QQ
          this.ruleForm.Isleader = this.addlist[0].Isleader
        }
      },
      handleCurrentChange(val) {
        let page = val
        this.initialize({ keyName: this.search, userStatu: -1, page: val, pageSize: 10 })
      },
      exportExcel() {
        /* generate workbook object from table */
        var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
        var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'), xlsxParam)

        /* get binary string as output */
        var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '审核情况表.xlsx')
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
        return wbout
      },
      changeForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert(this.addlist[0].UserID)
            if (this.ruleForm.sex == '男') {
              this.ruleForm.sex = 0
            } else {
              this.ruleForm.sex = 1
            }
            this.change({
              userID: this.UserID,
              jobNum: this.ruleForm.jobNum,
              realName: this.ruleForm.realName,
              sex: this.ruleForm.sex,
              iconUrl: '',
              email: this.ruleForm.email,
              departmentID: this.ruleForm.departmentID,
              roleID: this.ruleForm.roleID,
              workPhone: this.ruleForm.workPhone,
              mobelPhone: this.ruleForm.mobelPhone,
              weChatID: this.ruleForm.weChatID,
              qq: this.ruleForm.qq,
              Isleader: this.ruleForm.Isleader,

            }).then(() => {
              this.submitReset()
              this.initialize({ keyName: '', userStatu: -1, page: 1, pageSize: 10 })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      add() {
        this.ruleForm = {}
        this.dialogVisible = true
        // this.$refs["ruleForm"].resetFields()
      },
      submitReset() {
        this.dialogVisible = false
        this.showadd = false
      },
      newSetPass() {
        if (this.checkIds > 0) {
          let listid = ''
          this.checkIds.forEach(el => {
            listid += el + ','
          })
          listid = listid.substr(0, listid.length - 1)
          newSetPass({ strUserID: listid }).then((res) => {
            alert(res.Message)
          }).catch((error) => {
            console.log(error)
          })
        } else {
          alert('请勾选需要重置密码的员工')
        }
      },
      getListId(listId) {
        this.checkIds = listId
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert('submit!')
            this.increase({
              userName: this.ruleForm.userName,
              jobNum: this.ruleForm.jobNum,
              realName: this.ruleForm.realName,
              sex: this.ruleForm.sex,
              iconUrl: '',
              email: this.ruleForm.email,
              departmentID: this.ruleForm.departmentID,
              roleID: this.ruleForm.roleID,
              workPhone: this.ruleForm.workPhone,
              mobelPhone: this.ruleForm.mobelPhone,
              weChatID: this.ruleForm.weChatID,
              qq: this.ruleForm.qq,
              Isleader: this.ruleForm.Isleader ? this.ruleForm.Isleader : 0,
            }).then(() => {
              this.submitReset()
              this.initialize({ keyName: '', userStatu: -1, page: 1, pageSize: 10 })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      changedata(data) {
        this.addlist = data
      },
      dimission() {
        if (this.checkIds.length > 0) {
          let listid = ''
          this.checkIds.forEach(el => {
            listid += el + ','
          })
          listid = listid.substr(0, listid.length - 1)
          dimissionApi({ strUserID: listid }).then((res) => {
            alert(res.Message)
            this.initialize({ keyName: '', userStatu: -1, page: 1, pageSize: 10 })
          }).catch((error) => {
            console.log(error)
          })
        } else {
          alert('请勾选离职的员工')
        }
      },
      removedata() {
        if (this.checkIds.length > 0) {
          this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let listid = ''
            this.checkIds.forEach(el => {
              listid += el + ','
            })
            listid = listid.substr(0, listid.length - 1)
            this.removed({ strUserID: listid }).then(() => {
              this.initialize({ keyName: '', userStatu: -1, page: 1, pageSize: 10 })
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        } else {
          alert('请勾选需要删除的员工')
        }
      },
      // 配置工位
      configuration() {
        if (this.checkIds.length !== 1) {
          this.$message('请勾选需要配置工位的员工')
        } else {
          this.conDialogVisible = true
          getUserWorkStationList({ userId: this.checkIds[0] }).then(res => {
            if (parseInt(res.Code) === 1) {
              this.userStationList = res.Result
            }
          })
        }
      },
      add1() {
        this.userStationList.push({
          Id: this.userStationList.length,
          Line: { LineId: '' },
          WorkStation: { WorkstationId: '' },
          Tech: { TechId: '' },
          PrinterName: ''
        })
      },
      onSubmit() {
        this.jsonItem = []
        for (var i = 0; i < this.userStationList.length; i++) {
          var list = {
            Id: this.userStationList[i].Id,
            UserId: this.checkIds[0],
            LineId: this.userStationList[i].Line.LineId,
            WorkstationId: this.userStationList[i].WorkStation.WorkstationId,
            TechId: this.userStationList[i].Tech.TechId,
            PrinterName: this.userStationList[i].PrinterName
          }
          this.jsonItem.push(list)
        }
        console.log(this.jsonItem)
        commitUserWorkStation({ jsonString: JSON.stringify(this.jsonItem) }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.$message({
              type: 'success',
              message: '成功'
            })
          }
          this.conDialogVisible = false
        })
      },
      getLine() {
        getLineList({ keyName: '', page: 1, pageSize: 1000 }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.lineData = res.Result.Items
          }
        })
      },
      getStation() {
        getWorkStationList({ keyName: '', page: 1, pageSize: 1000 }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.stationData = res.Result.Items
          }
        })
      },
      getTech() {
        getTechPageList({ keyName: '', page: 1, pageSize: 1000 }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.techData = res.Result.Items
          }
        })
      },
      getDepartment() {
        getAllDepartmentList().then(res => {
          if (parseInt(res.Code) === 1) {
            this.departmentData = res.Result
          }

        })
      },
      getRole() {
        getAllRoleList().then(res => {
          if (parseInt(res.Code) === 1) {
            this.roleData = res.Result
          }
        })
      }
    },
    created() {
      this.initialize({ keyName: '', userStatu: -1, page: 1, pageSize: 10 })
      this.getLine()
      this.getStation()
      this.getTech()
      this.getDepartment()
      this.getRole()
    }
  }
</script>

<style lang="scss" scoped>
  .sizeBig {
    font-size: 16px;
  }

  .topBtn {
    height: 60px;
    width: 98%;
    margin: 0 auto;
    line-height: 60px;
    display: flex;
    justify-content: space-between;

  }

  .message {
    width: 98%;
    margin: 0 auto;
    height: 60px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(238, 238, 238, 1);
    font-size: 14px;

    .character {
      margin: 20px 0 21px 20px;
      color: #999999;

      .skip {
        color: #0095FF;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }

  .inputcontent {
    width: 98%;
    margin: 0 auto;
    height: 80px;
    position: relative;
    padding-top: 21px;
    box-sizing: border-box;

    .iconSearch {
      position: absolute;
      left: 277px;
      top: 30px;
      width: 20px;
      height: 20px;
      background-image: url('image/搜索.png');
      background-repeat: no-repeat;
      cursor: pointer;
    }

    .inSearch {
      width: 308px;
      height: 40px;
    }

  }

  .tablesize {
    width: 98%;
    margin: 0 auto;
  }

  .block {
    text-align: right;
    margin: 28px 20px 0 0;
  }

  .btnvessel {
    text-align: right;
  }

  .skip {
    color: #0095FF;
    cursor: pointer;
  }
</style>
